package com.zjl.media.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.cors.CorsConfig;
import io.netty.handler.codec.http.cors.CorsConfigBuilder;
import io.netty.handler.codec.http.cors.CorsHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author linfuxin Created on 2022-03-02 08:52:21
 */
public abstract class NettyChannelInitializer extends ChannelInitializer<Channel> {
    @Override
    protected void initChannel(Channel channel) throws Exception {
        ChannelPipeline pipeline = channel.pipeline();
        // 以下三个是Http的支持
        // http解码器
        pipeline.addLast(new HttpServerCodec());
        // 支持写大数据流
        pipeline.addLast(new ChunkedWriteHandler());
        // http聚合器
        pipeline.addLast(new HttpObjectAggregator(1024 * 64));
        // 跨域支持
        CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();
        pipeline.addLast(new CorsHandler(corsConfig));
        //添加自定义的助手类
        pipeline.addLast(getHandler());
    }

    protected abstract SimpleChannelInboundHandler<Object> getHandler();
}
